package com.pengpeng.redis.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * redis 过期监听
 * @author RocPengHua
 * @date 2022/8/9 20:40
 */
@Slf4j
@Component
public class KeyExpiredListener extends KeyExpirationEventMessageListener {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //获取失效key名称
        String expireKey = new String(message.getBody(), StandardCharsets.UTF_8);
        //获取key原本的value 获取不到 是null
        String expireKeyValue = redisTemplate.opsForValue().get("myKey");
        log.info("expireKey---"+expireKey);
        log.info("expireKeyValue---"+expireKeyValue);
        log.info("pattern----{}",new String(pattern));
    }
}
